package edu.ChildrensBooks.controller

import org.apache.jasper.compiler.Node.ParamsAction;

import edu.ChildrensBooks.model.Book
import edu.ChildrensBooks.service.BookService

class BookController {

	BookService bookService

	static scaffold = Book

	def submitBook = {
		Book validationBook = new Book(params.bookTitle, params.bookAuthor, params.description, params.isbn, Integer.parseInt(params.minGradeLevel), Integer.parseInt(params.maxGradeLevel), params.language, params.genre)
		if (params.uniqueId == null || params.uniqueId == "") { //This entails a new submission
			boolean validated = validationBook.validate()
			if (validated) {
				bookService.add(validationBook)
				render(view: "success")
			} else {
			
			render(view: "failure", model:[invalidBook:validationBook])
			}
		} else { //This entails an edit of a pre-exiting book
		boolean validated = validationBook.validate()
		if (validated) {
			bookService.update(validationBook, Integer.parseInt(params.uniqueId))
			render(view: "success")
		} else {
		
		render(view: "failure", model:[invalidBook:validationBook])
		}
		}
		
	}

	def deleteBook = {
		if (params.uniqueId == null || params.uniqueId == "") {
			//Nothing to delete
			List<Book> bookList = Book.getAll();
			render(view:"books",model:[bookList:bookList])
		} else {
		bookService.delete(Integer.parseInt(params.uniqueId))
		render(view: "success")
		}
		
	}

	def findBook = {
		List<Book> bookList = Book.getAll();
		render(view:"books",model:[bookList:bookList])
	}

	def updateView = {
		Book newBook = bookService.getBook(params.bookAuthor, params.bookTitle)
		List<String> genreList = ["General Leisure Reading", "Reading skills", "Math skills", "Health", "Science"]
		List<Integer> minList = [0, 1, 2, 3, 4, 5, 6]
		List<Integer> maxList = [0, 1, 2, 3, 4, 5, 6]
		render(view:"bookListBody", model:[book:newBook, genreList:genreList, minList:minList, maxList:maxList])
	}

	def randomQuote = {
		Book randomBook = bookService.getRandomBook()
		if (randomBook == null) {
			//no change to the page, because there are no books to choose a random one
		} else {
					List<String> genreList = ["General Leisure Reading", "Reading skills", "Math skills", "Health", "Science"]
					List<Integer> minList = [0, 1, 2, 3, 4, 5, 6]
					List<Integer> maxList = [0, 1, 2, 3, 4, 5, 6]
					render(view:"bookListBody", model:[book:randomBook, genreList:genreList, minList:minList, maxList:maxList])
		}
	}
}
